package client

import (
	"context"
	user2 "gitee.com/enjoy_5/user-rpc/proto/user"
	"gitee.com/xuxinzhi2206/corehub/nacos"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

const service = "user_rpc"
const group_name = "DEFAULT_GROUP"

func client(_ context.Context, hand func(c user2.UserClient) error) error {
	//发现服务
	addr, err := nacos.FindHealthService(service, group_name)
	if err != nil {
		return err
	}
	//建立一个GRPC的链接
	conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		return err
	}

	//延迟关闭链接
	defer conn.Close()

	//获取user client
	c := user2.NewUserClient(conn)
	//将client 传递给闭包函数并执行闭包内的内容
	return hand(c)
}

// 添加
func UserSave(ctx context.Context, req *user2.SaveUserRequest) (resp *user2.SaveUserResponse, err error) {
	err = client(ctx, func(c user2.UserClient) error {
		list, err := c.UserSave(ctx, req)
		if err != nil {
			return err
		}
		resp = list
		return nil
	})
	return
}

// 修改
func UserUpdate(ctx context.Context, req *user2.UpdUserRequest) (resp *user2.UpdUserResponse, err error) {
	err = client(ctx, func(c user2.UserClient) error {
		list, err := c.UserUpdate(ctx, req)
		if err != nil {
			return err
		}
		resp = list
		return nil
	})
	return
}

// 用户查询
func UserFind(ctx context.Context, req *user2.UserFirstRequest) (resp *user2.UserFirstResponse, err error) {
	err = client(ctx, func(c user2.UserClient) error {
		list, err := c.Userfind(ctx, req)
		if err != nil {
			return err
		}
		resp = list
		return nil
	})
	return
}

// 根据用户id数组获取用户列表
func UserList(ctx context.Context, req *user2.UserListRequest) (resp *user2.UserListResponse, err error) {
	err = client(ctx, func(c user2.UserClient) error {
		list, err := c.UserList(ctx, req)
		if err != nil {
			return err
		}
		resp = list
		return nil
	})
	return
}
